﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SD.Business;
using SD.DataAccess;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using SD.Commons;

namespace SD.Web.Iteration1.Program
{
    public partial class ProgramList : System.Web.UI.Page
    {
        /// <summary>
        /// Maintain the filter value
        /// </summary>
        public Collection<string> Filter
        {
            get
            {
                if (ViewState["Filter"] != null)
                {
                    return (Collection<string>)this.ViewState["Filter"];
                }
                else
                {
                    return null;
                }
            }

            set
            {
                this.ViewState["Filter"] = value;
            }
        }

        /// <summary>
        /// Maintain the sort value
        /// </summary>
        public string SortType
        {
            get
            {
                if (ViewState["sortType"] != null)
                {
                    return this.ViewState["sortType"].ToString();
                }
                else
                {
                    this.ViewState["sortType"] = "ProgramName";
                    return this.ViewState["sortType"].ToString();
                }
            }

            set
            {
                this.ViewState["sortType"] = value;
            }
        }

        /// <summary>
        /// Maintain the total pages of datagrid
        /// </summary>
        public int PageCount
        {
            get
            {
                return Convert.ToInt16(this.ViewState["PageCount"].ToString());
            }

            set
            {
                this.ViewState["PageCount"] = value;
            }
        }

        /// <summary>
        /// Check the status of sort and filter
        /// </summary>
        public int[] Flag
        {
            get
            {
                if (ViewState["Flag"] != null)
                {
                    return (int[])this.ViewState["Flag"];
                }
                else
                {
                    int[] flag = new int[2];
                    flag[0] = 0;
                    flag[1] = 0;
                    this.ViewState["Flag"] = flag;
                    return (int[])this.ViewState["Flag"];
                }
            }

            set
            {
                this.ViewState["Flag"] = value;
            }
        }

        /// <summary>
        /// Maintain the current page
        /// </summary>
        public int CurPage
        {
            get
            {
                if (this.ViewState["CurrentPage"] == null)
                    return 1;
                else
                    return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
            }

            set
            {
                this.ViewState["CurrentPage"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData(Filter, SortType);
            }
        }

        /// <summary>
        /// Fill the data to the form
        /// </summary>
        /// <param name="filter">type of filter</param>
        /// <param name="sortType">type of sort</param>
        public void LoadData(Collection<string> filter, string sortType)
        {
            ProgramBUS programBus = new ProgramBUS();
            List<ProgramView> pro = new List<ProgramView>();
            //sort type program name
            if (sortType == "ProgramName")
            {
                if (Flag[0] % 2 == 0)
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderBy(item => item.ProgramName).ToList();
                else
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.ProgramName).ToList();
            }
            //sort type description
            if (sortType == "Description")
            {
                if (Flag[0] % 2 == 0)
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderBy(item => item.Description).ToList();
                else
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.Description).ToList();
            }
            //sort type contact name
            if (sortType == "ContactName")
            {
                if (Flag[0] % 2 == 0)
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderBy(item => item.Surname).ToList();
                else
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.Surname).ToList();
            }
            //sort type isactive
            if (sortType == "IsActive")
            {
                if (Flag[0] % 2 == 0)
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderBy(item => item.IsActive).ToList();
                else
                    pro = programBus.ListProgram(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.IsActive).ToList();
            }
                        
            //total page
            PageCount = (int)Math.Ceiling(pro.Count / 10.0);
            if (PageCount == 0)
            {
                PageCount = 1;
            }
            
            //check link button to invisible or visible
            if (CurPage == 1)
            {
                btnFirst.Visible = false;
                btnPrevious.Visible = false;
                btnLast.Visible = true;
                btnNext.Visible = true;
            }
            if (CurPage == PageCount && PageCount == 1)
            {
                btnFirst.Visible = false;
                btnPrevious.Visible = false;
                btnLast.Visible = false;
                btnNext.Visible = false;
            }
            else
            {
                if (CurPage == PageCount)
                {
                    btnFirst.Visible = true;
                    btnPrevious.Visible = true;
                    btnLast.Visible = false;
                    btnNext.Visible = false;
                }
            }
            if (CurPage > 1 && CurPage < PageCount)
            {
                btnFirst.Visible = true;
                btnPrevious.Visible = true;
                btnLast.Visible = true;
                btnNext.Visible = true;
            }
            //show on grid view
            GridViewProgram.DataSource = pro.Skip((CurPage - 1) * 10).Take(10);
            GridViewProgram.DataBind();
        }

        /// <summary>
        /// Event handles the filter action
        /// </summary>
        protected void FilterByLetters_Command(object sender, CommandEventArgs e)
        {
            //sort type
            CurPage = 1;
            Filter = StringTools.GetLetterGroup(e.CommandName);
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Create button click event
        /// </summary>
        protected void CreateButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddProgram.aspx");
        }

        /// <summary>
        /// checkbox checked changed event
        /// </summary>
        protected void CheckBoxInactive_CheckedChanged(object sender, EventArgs e)
        {
            CurPage = 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Paging
        /// </summary>
        protected void btnLast_Click(object sender, EventArgs e)
        {
            CurPage = PageCount;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Paging
        /// </summary>
        protected void btnFirst_Click(object sender, EventArgs e)
        {
            CurPage = 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Paging
        /// </summary>
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            CurPage -= 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Paging
        /// </summary>
        protected void btnNext_Click(object sender, EventArgs e)
        {
            CurPage += 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Handle the sorting action
        /// </summary>
        protected void GridViewProgram_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sort = e.SortExpression;
            //sort program name
            if (sort == "ProgramName")
            {
                if (Flag[1] == 0)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 0;
                }
                SortType = "ProgramName";
                LoadData(Filter, SortType);
            }
            //sort description
            if (sort == "Description")
            {
                if (Flag[1] == 1)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 1;
                }
                SortType = "Description";
                LoadData(Filter, SortType);
            }
            //sort contact name
            if (sort == "ContactName")
            {
                if (Flag[1] == 2)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 2;
                }
                SortType = "ContactName";
                LoadData(Filter, SortType);
            }
            //sort is active
            if (sort == "IsActive")
            {
                if (Flag[1] == 3)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 3;
                }
                SortType = "IsActive";
                LoadData(Filter, SortType);
            }
        }

        /// <summary> 
        /// Handles the Command event of the LinkButtonOrganizationName control. 
        /// </summary> 
        /// <param name="sender">The source of the event.</param> 
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void LinkButtonPROName_Command(object sender, CommandEventArgs e)
        {
            new ProgramBUS().ChangeProgramStatus(Convert.ToInt16(e.CommandName), true);
            Response.Redirect("EditProgram.aspx?programId=" + e.CommandName);
        }

        protected void GridViewProgram_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[0].HasControls())
                {
                    LinkButton LinkButtonPROName = ((LinkButton)e.Row.Cells[0].Controls[1]);
                    var programView = e.Row.DataItem as SD.DataAccess.ProgramView;
                    if (programView.IsActive == false)
                        LinkButtonPROName.Attributes.Add("onclick",
                            "if(confirm(\"Do you want to make this Program active?\") == true)"
                            + "{return true;} else {window.location.href='EditProgram.aspx?programId= " + programView.ProgramId + "'; return false;}");
                }
            }
        }
    }
}